package cn.edu.hznu.notebook.service;

import java.util.List;
import java.util.Optional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.edu.hznu.notebook.dao.NoteDao;
import cn.edu.hznu.notebook.dao.NotebookDao;
import cn.edu.hznu.notebook.entity.Notebook;
import cn.edu.hznu.notebook.entity.User;

@Service("NotebookService")
@Transactional(rollbackFor = {Exception.class})
public class NotebookServiceImpl implements NotebookService{
	
	@Autowired
	NotebookDao notebookDao;
	
	@Autowired
	NoteDao noteDao;

	@Override
	public void addNewNotebook(Notebook notebook) throws Exception {
		Optional.ofNullable(notebook.getUser())
				.orElseThrow(() -> 
					new Exception("The notebook's user should not be null."));
		this.notebookDao.save(notebook);
	}

	@Override
	public Notebook getNotebookById(Integer id) {
		return this.notebookDao.findById(id);
	}

	@Override
	public List<Notebook> getNotebooksByUser(User user) {
		List<Notebook> notebooks = this.notebookDao.findByUser(user);
		notebooks.forEach(notebook -> notebook.setUser(user));
		return notebooks;
	}

	@Override
	public void updateNotebookInfo(Notebook notebook) throws Exception {
		Optional.ofNullable(notebook.getUser())
				.orElseThrow(() ->
						new Exception("The notebook's user should not be null."));
		this.notebookDao.update(notebook);
	}

	@Override
	public void deleteNotebook(Notebook notebook) throws Exception {
		this.notebookDao.delete(notebook);
		this.noteDao.deleteByNotebook(notebook);
	}

	@Override
	public void deleteNotebook(Integer id) throws Exception {
		this.notebookDao.deleteById(id);
		Notebook notebook = new Notebook();
		notebook.setId(id);
		this.noteDao.deleteByNotebook(notebook);
	}

}
